using System.Net;

namespace AnalyStock.DataManage;

public static class HttpClientUtility
{
    public static async Task<string> HttpClientPostAsync(Uri url, object datajson)
    {
        //在使用GB2312编码前需要先使用Encoding.RegisterProvider方法注册
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        using HttpClient httpClient = new(); //handler             
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.Timeout = new TimeSpan(0, 0, 5);
        //转为链接需要的格式       
        using HttpContent httpContent = JsonContent.Create(datajson);
        //请求       
        using var response = await httpClient.PostAsync(url, httpContent).ConfigureAwait(false);
        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        }

        throw new Exception($"{url}数据下载错误:{response.ReasonPhrase}");
    }

    public static async Task<string> HttpClientGetAsync(Uri url)
    {
        //在使用GB2312编码前需要先使用Encoding.RegisterProvider方法注册
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        //服务器会返回GZip压缩后的数据,数据要求解压
        var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip };
        using HttpClient httpClient = new(handler); //handler             
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
        httpClient.Timeout = new TimeSpan(0, 0, 5);
        //请求      
        using var response = await httpClient.GetAsync(url).ConfigureAwait(false);
        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        }

        throw new Exception($"{url}数据下载错误:{response.ReasonPhrase}");
    }
}